package com.dlb.andorid.fragment;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.dlb.andorid.App;
import com.dlb.andorid.ProductAdapter;
import com.dlb.andorid.R;
import com.dlb.andorid.XContract;
import com.dlb.andorid.activity.FwgcActivity;
import com.dlb.andorid.activity.JrbkActivity;
import com.dlb.andorid.activity.MainActivity;
import com.dlb.andorid.activity.ProductDetailActivity;
import com.dlb.andorid.activity.SuperMarketActivity;
import com.dlb.andorid.activity.WebActivity;
import com.dlb.andorid.activity.ZbhdActivity;
import com.dlb.andorid.bean.ImgBean;
import com.dlb.andorid.bean.ProductBean;
import com.dlb.andorid.bean.SecTypeBean;
import com.dlb.andorid.bean.ServerResult;
import com.dlb.andorid.presenter.HomePresenter;
import com.kwan.xframe.mvp.view.activity.BaseWebActivity;
import com.kwan.xframe.mvp.view.fragment.BasePageItemFragment;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.loader.ImageLoader;

import java.util.ArrayList;
import java.util.List;

public class HomeFragment extends BasePageItemFragment implements XContract.IHomeView, OnLoadMoreListener, OnRefreshListener {

	public static HomeFragment newInstance() {
		HomeFragment fragment = new HomeFragment();
		Bundle args = new Bundle();
		fragment.setArguments(args);
		return fragment;
	}

	@Override
	protected String getItemTag() {
		return "Home";
	}


	RecyclerView rv_type, rv_home;

	BaseQuickAdapter<SecTypeBean, BaseViewHolder> mTypeAdapter;
	BaseQuickAdapter<ProductBean, BaseViewHolder> mHomeAdapter;

	HomePresenter mPresenter;
	List<SecTypeBean> mTypes = new ArrayList<>();
	List<ProductBean> mProducts = new ArrayList<>();

	int mCurrentSelectTypePosition = 0;

	protected RefreshLayout refreshLayout;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		mPresenter = new HomePresenter(this);

		refreshLayout = mContentView.findViewById(R.id.refreshLayout);
		refreshLayout.setOnLoadMoreListener(this);
		refreshLayout.setOnRefreshListener(this);

		rv_type = mContentView.findViewById(R.id.rv_type);
		mTypeAdapter = new BaseQuickAdapter<SecTypeBean, BaseViewHolder>(R.layout.list_item_home_type, mTypes) {
			@Override
			protected void convert(BaseViewHolder helper, SecTypeBean item) {

				if (mCurrentSelectTypePosition == helper.getLayoutPosition()) {
					helper.setBackgroundRes(R.id.tv_name, R.drawable.shape_home_type_selected);
					helper.setTextColor(R.id.tv_name, Color.WHITE);
				} else {
					helper.setBackgroundRes(R.id.tv_name, R.drawable.shape_home_type_normal);
					helper.setTextColor(R.id.tv_name, getResources().getColor(R.color.colorPrimary));
				}

				helper.setText(R.id.tv_name, item.getName());
			}
		};

		mTypeAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
			@Override
			public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
				mCurrentSelectTypePosition = position;
				page = 1;
				isLoadMore = false;
				mPresenter.getProduct(mTypes.get(position).getId(), page, pageNum);
				mTypeAdapter.notifyDataSetChanged();
			}
		});

		rv_type.setLayoutManager(new LinearLayoutManager(mBaseActivity, LinearLayoutManager.HORIZONTAL, false));
		rv_type.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
		rv_type.setLayerType(View.LAYER_TYPE_HARDWARE, null);
		rv_type.setHasFixedSize(true);
		//解决更新 闪烁
		rv_type.setItemAnimator(null);
		rv_type.setNestedScrollingEnabled(false);
		rv_type.setAdapter(mTypeAdapter);

		rv_home = mContentView.findViewById(R.id.rv_home);

		mHomeAdapter = new ProductAdapter(mProducts);

		rv_home.setLayoutManager(new GridLayoutManager(mBaseActivity, 2, LinearLayoutManager.VERTICAL, false));
		rv_home.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
		rv_home.setLayerType(View.LAYER_TYPE_HARDWARE, null);
		rv_home.setLayerType(View.LAYER_TYPE_NONE, null);
		rv_home.setHasFixedSize(true);
		//解决更新 闪烁
		rv_home.setItemAnimator(null);
		rv_home.setNestedScrollingEnabled(false);
		rv_home.setAdapter(mHomeAdapter);

		mHomeAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
			@Override
			public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
				Bundle bundle = new Bundle();
				bundle.putLong("id", mProducts.get(position).getId());
				go2Activity(ProductDetailActivity.class, bundle, false);
			}
		});

		mHomeAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
			@Override
			public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
				//toastMsg(""+mProducts.get(position).getId());
				Log.e("kwan", "car:" + mProducts.get(position).getId());
				if (view.getId() == R.id.iv_car) {
					Log.e("kwan", "car:" + mProducts.get(position).getId());
					mBaseActivity.showProgress("");
					mPresenter.addCar(mProducts.get(position).getId(), App.mUserInfo.getUid(), 1, mProducts.get(position).getType_id(), mProducts.get(position).getSale_price());
				}
			}
		});

		mContentView.findViewById(R.id.ll_wymc).setOnClickListener(this);
		mContentView.findViewById(R.id.ll_tcsc).setOnClickListener(this);
		mContentView.findViewById(R.id.ll_zbhd).setOnClickListener(this);
		mContentView.findViewById(R.id.ll_cpdq).setOnClickListener(this);
		mContentView.findViewById(R.id.ll_wsms).setOnClickListener(this);
		mContentView.findViewById(R.id.ll_xsqg).setOnClickListener(this);
		mContentView.findViewById(R.id.ll_jrbk).setOnClickListener(this);
		mContentView.findViewById(R.id.ll_fwgc).setOnClickListener(this);
		mContentView.findViewById(R.id.ll_fpzq).setOnClickListener(this);
		mContentView.findViewById(R.id.ll_kfzx).setOnClickListener(this);
		mContentView.findViewById(R.id.ll_cpdq).setOnClickListener(this);
		mContentView.findViewById(R.id.ll_xsqg).setOnClickListener(this);

	}


	@Override
	public void onResume() {
		super.onResume();
	}


	@Override
	public void onClick(View v) {
		super.onClick(v);
		switch (v.getId()) {
			case R.id.ll_wymc:
				TypeFragment.classId = 1;
				((MainActivity) mBaseActivity).vp_content.setCurrentItem(2);
				break;
			case R.id.ll_tcsc:
//				TypeFragment.classId = 2;
//				((MainActivity) mBaseActivity).vp_content.setCurrentItem(2);


				go2Activity(SuperMarketActivity.class, null, false);

				break;
			case R.id.ll_zbhd:
//				TypeFragment.classId = 3;
//				((MainActivity) mBaseActivity).vp_content.setCurrentItem(2);
				go2Activity(ZbhdActivity.class, null, false);
				break;
			case R.id.ll_jrbk:
				go2Activity(JrbkActivity.class, null, false);
				break;
			case R.id.ll_wsms: {

				Bundle bundle = new Bundle();
				bundle.putString("url", "http://www.dilinbang.com/show.php");
				bundle.putString("title", "我晒美食");
				bundle.putInt("mode", BaseWebActivity.MODE_WEB);
				go2Activity(WebActivity.class, bundle, false);

				//go2Activity(FoodActivity.class, null, false);
				break;
			}
			case R.id.ll_kfzx: {
				Bundle bundle = new Bundle();
				bundle.putString("url", "http://www.dilinbang.com/kf_service.php");
				bundle.putString("title", "客服中心");
				bundle.putInt("mode", BaseWebActivity.MODE_WEB);
				go2Activity(WebActivity.class, bundle, false);
				break;
			}
			case R.id.ll_fpzq: {
				Bundle bundle = new Bundle();
				bundle.putString("url", "http://www.dilinbang.com/fp_prefecture.php");
				bundle.putString("title", "扶贫专区");
				bundle.putInt("mode", BaseWebActivity.MODE_WEB);
				go2Activity(WebActivity.class, bundle, false);
				break;
			}
			case R.id.ll_fwgc:
				go2Activity(FwgcActivity.class, null, false);
				break;
			case R.id.ll_cpdq: {
				Bundle bundle = new Bundle();
				bundle.putString("url", "http://www.dilinbang.com/menu.php");
				bundle.putString("title", "菜谱大全");
				bundle.putInt("mode", BaseWebActivity.MODE_WEB);
				go2Activity(WebActivity.class, bundle, false);
				break;
			}
			case R.id.ll_xsqg:
				toastMsg("暂未开放");
				break;
		}
	}


	@Override
	public void onPause() {
		super.onPause();
	}

	@Override
	public void onStop() {
		super.onStop();
	}


	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	@Override
	protected int getContentViewId() {
		return R.layout.fragment_home;
	}

	//第一次获取数据
	@Override
	public void fetchData() {
		mPresenter.getBanner();
		mPresenter.getSecType(1);
	}

	@Override
	public void onDestroyView() {
		super.onDestroyView();
	}

	@Override
	public String getPageName() {
		return null;
	}

	Banner banner;

	@Override
	public void getBannerSuccess(List<ImgBean> result) {
		try {
			if (result == null || result.size() == 0) return;
			if (banner == null) {
				banner = mContentView.findViewById(R.id.banner);
				//设置banner样式
				//banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR_TITLE);
				//设置图片加载器
				banner.setImages(result);
				banner.setImageLoader(new ImageLoader() {
					@Override
					public void displayImage(Context context, Object path, ImageView imageView) {
						//Glide 加载图片简单用法
						Log.e("kwan", ((ImgBean) path).getPic_url());
						Glide.with(context).load(((ImgBean) path).getPic_url()).apply(App.mGildOptions).into(imageView);
					}
				});
				//设置图片集合

				//设置banner动画效果
				banner.setBannerAnimation(Transformer.DepthPage);
				//设置标题集合（当banner样式有显示title时）
				//banner.setBannerTitles(titles);
				//设置自动轮播，默认为true
				//banner.isAutoPlay(false);
				//设置轮播时间
				banner.setDelayTime(5000);
				//设置指示器位置（当banner模式中有指示器时）
				banner.setIndicatorGravity(BannerConfig.RIGHT);
				banner.setOnBannerListener(new OnBannerListener() {
					@Override
					public void OnBannerClick(int position) {
//						Bundle bundle = new Bundle();
//						bundle.putInt("mode", BaseWebActivity.MODE_WEB);
//						bundle.putString("url", result.get(position).getUrl());
//						bundle.putString("title", result.get(position).getTitle());
//						JLog.e("kwan", "banner click " + position);
//						go2Activity(WebActivity.class, bundle, false);
					}
				});

				//banner设置方法全部调用完毕时最后调用

				banner.setFocusable(true);
				banner.setFocusableInTouchMode(true);
				banner.requestFocus();
				banner.start();

			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void getSecTypeSuccess(List<SecTypeBean> data) {

		mTypes.clear();
		mTypes.addAll(data);
		mTypeAdapter.notifyDataSetChanged();
		mPresenter.getProduct(mTypes.get(0).getId(), 1, pageNum);

	}

	@Override
	public void getProductsSuccess(List<ProductBean> data) {
		refreshLayout.finishRefresh();
		refreshLayout.finishLoadMore();

		if (isLoadMore) {

			if (data == null)
				return;

			mProducts.addAll(data);
			mHomeAdapter.setNewData(mProducts);
		} else {
			mProducts.clear();
			if (data != null)
				mProducts.addAll(data);

			mHomeAdapter.setNewData(mProducts);
		}

	}


	int page = 1;
	int pageNum = 10;
	boolean isLoadMore;

	@Override
	public void onRefresh(@NonNull RefreshLayout refreshLayout) {
		page = 1;
		isLoadMore = false;
		mPresenter.getProduct(mTypes.get(mCurrentSelectTypePosition).getId(), page, pageNum);
	}

	@Override
	public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
		isLoadMore = true;
		page++;
		mPresenter.getProduct(mTypes.get(mCurrentSelectTypePosition).getId(), page, pageNum);
	}

	@Override
	public void addCarSuccess(ServerResult data) {
		dismissProgress();
		toastMsg(data.getMsg());
	}


}
